package com.shiningstars.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.shiningstars.R;
import com.shiningstars.database.DatabaseHandler;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.service.FeedbackNotifyService;
import com.shiningstars.service.FeedbackSendService;
import com.shiningstars.tools.DatePickerFragment;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.valuebeans.Feedback;

@SuppressLint("SimpleDateFormat")
public class TeacherFeedback0Activity extends FragmentActivity implements Constants, Messages, Config {

	Feedback feedback;

	RadioGroup radioGroupFeedbackYesNo;
	RadioButton feedbackYes;
	RadioButton feedbackNo;
	Spinner spinnerCenterName;
	TextView textViewPathshalaDate;
	RadioGroup radioGroupReason;
	RadioButton reasonAbsent;
	RadioButton reasonOther;
	EditText editTextReason;
	LinearLayout linearLayout2;

	boolean submitFeedback = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_teacher_feedback_0);

			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
			SplashPageActivity.showSplash = false;

			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

			radioGroupFeedbackYesNo = (RadioGroup) findViewById(R.id.tf0RadioGroup1);
			feedbackYes = (RadioButton) findViewById(R.id.tf0RadioButton1);
			feedbackNo = (RadioButton) findViewById(R.id.tf0RadioButton2);
			spinnerCenterName = (Spinner) findViewById(R.id.tf0Spinner1);
			textViewPathshalaDate = (TextView) findViewById(R.id.tf0TextView1);
			radioGroupReason = (RadioGroup) findViewById(R.id.tf0RadioGroup2);
			reasonAbsent = (RadioButton) findViewById(R.id.tf0RadioButton3);
			reasonOther = (RadioButton) findViewById(R.id.tf0RadioButton4);
			editTextReason = (EditText) findViewById(R.id.tf0EditText1);

			linearLayout2 = (LinearLayout) findViewById(R.id.tf0LinearLayout2);
			linearLayout2.setVisibility(View.INVISIBLE);

			Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int date = c.get(Calendar.DATE);

			String name = Utilities.getSharedPreference(getApplicationContext(), NAME);
			String feedbackDate = Utilities.getDate(date, month, year);

			feedback = new Feedback();

			String mobileNumber = Utilities.getSharedPreference(getApplicationContext(), MOBILE_NUMBER);
			String imeiNumber = Utilities.getSharedPreference(getApplicationContext(), IMEI_NUMBER);

			feedback.setMobileNumber(mobileNumber);
			feedback.setImeiNumber(imeiNumber);
			feedback.setDate(c.getTimeInMillis());
			feedback.setMode(APP);
			feedback.setIsSynced(N);
			feedback.setIsNotified(N);
			feedback.setIsRead(N);

			feedback.setQuestion2(name);
			feedback.setQuestion4(feedbackDate);

		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.feedback_menu, menu);
			menu.removeItem(R.id.feedback_back);
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			if (NEXT.equals(item.getTitle())) {
				if (submitFeedback) {
					Intent i = new Intent(TeacherFeedback0Activity.this, TeacherFeedback1Activity.class);
					startActivity(i);
					finish();
				} else if (validate()) {
					AlertDialog.Builder builder = new AlertDialog.Builder(TeacherFeedback0Activity.this);

					builder.setMessage(FEEDBACK_SUBMIT);
					builder.setCancelable(false);
					builder.setNegativeButton(CANCEL, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
						}
					});
					builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());
							long rowId = databaseHandler.saveFeedback(feedback);

							if (rowId != -1) {
								if (!Utilities.isRunning(getApplicationContext(), FeedbackSendService.class.getName())) {
									startService(new Intent(getApplicationContext(), FeedbackSendService.class));
								}

								if (!Utilities.isRunning(getApplicationContext(), FeedbackNotifyService.class.getName())) {
									startService(new Intent(getApplicationContext(), FeedbackNotifyService.class));
								}

								Intent i = new Intent(TeacherFeedback0Activity.this, MyFeedbackActivity.class);
								startActivity(i);
								finish();
							}
						}
					});

					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(TeacherFeedback0Activity.this);

			builder.setMessage(FEEDBACK_CANCEL);
			builder.setCancelable(false);
			builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Intent i = null;

					String currentRole = Utilities.getSharedPreference(getApplicationContext(), CURRENT_ROLE);
					if (ADMIN.equals(currentRole)) {
						i = new Intent(TeacherFeedback0Activity.this, AdminActivity.class);
					} else if (TEACHER.equals(currentRole)) {
						i = new Intent(TeacherFeedback0Activity.this, MyFeedbackActivity.class);
					}

					startActivity(i);
					finish();
				}
			});
			builder.setNegativeButton(CANCEL, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {

				}
			});

			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}
	}

	public void showDatePickerDialog(View v) {
		try {
			DialogFragment newFragment = new DatePickerFragment(com.shiningstars.R.id.tf0TextView1);
			newFragment.show(getSupportFragmentManager(), DATE_PICKER);
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}
	}

	public void feedbackYes(View v) {
		try {
			submitFeedback = true;
			linearLayout2.setVisibility(View.INVISIBLE);

			feedback.setQuestion53(BLANK);
			feedback.setQuestion54(BLANK);
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}
	}

	public void feedbackNo(View v) {
		try {
			submitFeedback = false;
			linearLayout2.setVisibility(View.VISIBLE);

			absent(v);

			String centerName = Utilities.getSharedPreference(getApplicationContext(), CENTER);
			spinnerCenterName.setSelection(Utilities.getCenterId(centerName), true);

			Calendar calendar = Calendar.getInstance();
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

			if (dayOfWeek < 7) {
				calendar.add(Calendar.DAY_OF_WEEK, -1 * dayOfWeek);
			}

			DateFormat df = new SimpleDateFormat(EEE);
			String day = df.format(calendar.getTime());

			if (SATURDAY.equals(day)) {
				String pathshalaDate = Utilities.getDate(calendar.get(Calendar.DATE), calendar.get(Calendar.MONTH),
						calendar.get(Calendar.YEAR));
				textViewPathshalaDate.setText(pathshalaDate);
			}

			feedback.setQuestion5(BLANK);
			feedback.setQuestion6(BLANK);
			feedback.setQuestion7(BLANK);
			feedback.setQuestion8(BLANK);
			feedback.setQuestion9(BLANK);
			feedback.setQuestion10(BLANK);
			feedback.setQuestion11(BLANK);
			feedback.setQuestion12(BLANK);
			feedback.setQuestion13(BLANK);
			feedback.setQuestion14(BLANK);
			feedback.setQuestion15(BLANK);
			feedback.setQuestion16(BLANK);
			feedback.setQuestion17(BLANK);
			feedback.setQuestion18(BLANK);
			feedback.setQuestion19(BLANK);
			feedback.setQuestion20(BLANK);
			feedback.setQuestion21(BLANK);
			feedback.setQuestion22(BLANK);
			feedback.setQuestion23(BLANK);
			feedback.setQuestion24(BLANK);
			feedback.setQuestion25(BLANK);
			feedback.setQuestion26(BLANK);
			feedback.setQuestion27(BLANK);
			feedback.setQuestion28(BLANK);
			feedback.setQuestion29(BLANK);
			feedback.setQuestion30(BLANK);
			feedback.setQuestion31(BLANK);
			feedback.setQuestion32(BLANK);
			feedback.setQuestion33(BLANK);
			feedback.setQuestion34(BLANK);
			feedback.setQuestion35(BLANK);
			feedback.setQuestion36(BLANK);
			feedback.setQuestion37(BLANK);
			feedback.setQuestion38(BLANK);
			feedback.setQuestion39(BLANK);
			feedback.setQuestion40(BLANK);
			feedback.setQuestion41(BLANK);
			feedback.setQuestion42(BLANK);
			feedback.setQuestion43(BLANK);
			feedback.setQuestion44(BLANK);
			feedback.setQuestion45(BLANK);
			feedback.setQuestion46(BLANK);
			feedback.setQuestion47(BLANK);
			feedback.setQuestion48(BLANK);
			feedback.setQuestion49(BLANK);
			feedback.setQuestion50(BLANK);
			feedback.setQuestion51(BLANK);
			feedback.setQuestion52(BLANK);

		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}
	}

	public void absent(View v) {
		try {
			reasonAbsent.setChecked(true);
			editTextReason.setText(BLANK);
			editTextReason.setEnabled(false);
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}
	}

	public void otherReason(View v) {
		try {
			editTextReason.setEnabled(true);
			editTextReason.requestFocus();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), TeacherFeedback0Activity.class.getName(), e);
		}
	}

	private boolean validate() {
		boolean isValid = true;
		String errorMessage = null;

		if (spinnerCenterName.getSelectedItemId() == 0) {
			isValid = false;
			errorMessage = INVALID_CENTER_NAME;
			spinnerCenterName.requestFocus();
		} else {
			feedback.setQuestion1(spinnerCenterName.getSelectedItem().toString());
		}

		String pathshalaDate = textViewPathshalaDate.getText().toString();
		if (isValid && NO_DATE_SELECTED.equals(pathshalaDate)) {
			isValid = false;
			errorMessage = INVALID_PATHSHALA_DATE;
			textViewPathshalaDate.requestFocus();
		} else {
			feedback.setQuestion3(pathshalaDate);
		}

		int radioButtonId = radioGroupReason.getCheckedRadioButtonId();
		if (isValid && radioButtonId == reasonAbsent.getId()) {
			feedback.setQuestion53(Y);
			feedback.setQuestion54(BLANK);
		} else if (isValid && radioButtonId == reasonOther.getId()) {

			String reason = editTextReason.getText().toString();

			if (Utilities.isBlankString(reason)) {
				isValid = false;
				errorMessage = INVALID_REASON;
				editTextReason.requestFocus();
			} else {
				feedback.setQuestion53(N);
				feedback.setQuestion54(reason);
			}
		}

		if (!isValid) {
			AlertDialog.Builder builder = new AlertDialog.Builder(TeacherFeedback0Activity.this);

			builder.setMessage(errorMessage);
			builder.setCancelable(false);
			builder.setTitle(ERROR);
			builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			});

			AlertDialog alert = builder.create();
			alert.show();
		}

		return isValid;
	}

	@Override
	protected void onPause() {
		super.onPause();
		SplashPageActivity.showSplash = true;
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (SplashPageActivity.showSplash) {
			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View popupView = layoutInflater.inflate(R.layout.activity_splash_page, null);
			final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);

			findViewById(R.id.tf0Q53).post(new Runnable() {
				public void run() {
					popupWindow.showAtLocation(findViewById(R.id.tf0Q53), Gravity.CENTER, 0, 0);
				}
			});

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if (null != popupWindow && popupWindow.isShowing()) {
						popupWindow.dismiss();
					}
				}
			}, SPLASH_TIME_OUT);

			SplashPageActivity.showSplash = false;
		}
	}
}